<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<!--
			
			假设现在从后台接受了一段关于访客的信息数据(添加新的访客信息从info里面按照顺序拿取),请实现问题一.gif的效果.
			
		-->
		<button>添加一条新的访客信息</button>
		<button>删除选中</button>
		<button>从小到大</button>
		<table border="1" cellspacing="0" cellpadding="10">
			<tr>
				<th>序列号</th>
				<th>姓名</th>
				<th>年龄</th>
				<th>操作</th>
				<th>选择</th>
			</tr>
		</table>
		<script type="text/javascript">
			var info = [
				{ name: "胡杭", age: 16 },
				{ name: "胜明", age: 22 },
				{ name: "军毅", age: 21 },
				{ name: "晓华", age: 13 },
				{ name: "盛聪", age: 23 },
				{ name: "侦剑", age: 32 },
				{ name: "红翔", age: 25 },
				{ name: "超维", age: 18 },
				{ name: "士琪", age: 22 },
				{ name: "艳华", age: 20 }
			]
			var btns = document.querySelectorAll("button");
			var tb = document.querySelector("table tbody");
			var id = 0;

			/*
			 *添加新的访客信息 及添加删除功能
			 */
			btns[0].addEventListener("click", function() {
				id >= 10 ? id = 1 : id++;
				tb.innerHTML += "<tr data-id = " + id + "><td>" + id + "</td><td>" + info[id - 1].name + "</td><td>" + info[id - 1].age + "</td><th><button class = 'delete'  data-id = " + id + ">删除</button></th><th><input type='checkbox'/></th></tr>";
				var deletes = document.getElementsByClassName("delete");
				var deletes = document.querySelectorAll(".delete");
				for(var i = 0; i < deletes.length; i++) {
					deletes[i].addEventListener("click", function() {
						this.parentNode.parentNode.remove();
					})
				}
			})

			//事件委托
			tb.addEventListener("click", function(e) {
				console.log(e.target.nodeName);
				if(e.target.nodeName == "BUTTON") {
					e.target.parentNode.parentNode.remove();
				}
			})

			/*
			 * 删除选中功能
			 */
			btns[1].addEventListener("click", function() {
				var now_all_boxs = document.querySelectorAll("input[type=checkbox]");
				for(var i = 0; i < now_all_boxs.length; i++) {
					if(now_all_boxs[i].checked) {
						now_all_boxs[i].parentNode.parentNode.remove();
					}
				}
			})

			/*
			 * 从小到大排序
			 */
			btns[2].addEventListener("click", function() {
				var now_all_trs = document.querySelectorAll("tr:not(:first-of-type)");
				var new_all_trs = []
				for(var i = 0; i < now_all_trs.length; i++) {
					new_all_trs.push(now_all_trs[i]);
				}
				new_all_trs.sort(function(age1,age2) {
					var n1 = parseInt(age1.cells[2].innerHTML);
					var n2 = parseInt(age2.cells[2].innerHTML);
					return n1 - n2;
				})
				for(var i = 0; i < new_all_trs.length; i++) {
					tb.appendChild(new_all_trs[i])
				}
			})
		</script>
	</body>

</html>